package com.example.demo.shiro;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.ShiroFilter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 自定义Realm
 * @author zzy
 * 拦截器，权限设置
 */
@Configuration
public class ShiroConfig {
    /**
     * 创建ShiroFilterFactoryBean
     *
     */
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean( @Qualifier("securityManager") DefaultWebSecurityManager securityManager) {

        System.out.println("过滤器启动");

        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        //添加内置过滤器
        /**
         * Shiro内置过滤器，可实现权限相关的拦截器
         * 常用过滤器:
         *      anon:游客 (无需认证即可访问）
         *      authc: 必须认证才可访问
         *      user: 如果使用rememberMe（记住账号密码，有缓存）
         *      perms：该资源必须得到资源权限才能访问
         *      role: 该资源必须得到角色权限才可以访问
         */
        Map<String,String> map = new LinkedHashMap<String,String>();
//        map.put(路径,过滤器名称)
        map.put("/two","anon");
        map.put("/one","anon");
        //登录页面设置
        shiroFilterFactoryBean.setLoginUrl("/login");
        //设置过滤器
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        System.out.println("过滤器过滤成功"
                );
        return shiroFilterFactoryBean;
    }

    /**
     * 创建DefaultWebSecurityManager
     */
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {


        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();

        securityManager.setRealm(userRealm);

        return securityManager;
    }
    /**
     * 创建Realm
     */
    @Bean(name = "userRealm")
    public UserRealm getRealm() {
        System.out.println("创建权限对象");
        return new UserRealm();
    }
}
